package qc.module.ehs.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qc.common.core.enums.EhsWarehouseInventoryOperateTypeEnum;
import qc.common.core.exception.QCPromptException;
import qc.common.core.unify.QCUnifyReturnValue;
import qc.common.core.utils.DateUtil;
import qc.common.core.utils.IdentifierUtil;
import qc.module.ehs.dto.warehouseinventory.WareHouseInventoryAddDto;
import qc.module.ehs.dto.warehouseinventory.WareHouseInventoryDto;
import qc.module.ehs.dto.warehouseinventory.WareHouseInventoryQueryConditionDto;
import qc.module.ehs.entity.EhsWarehouseInventory;
import qc.module.ehs.mapper.EhsWarehouseInventoryMapper;
import qc.module.ehs.repository.EhsWarehouseInventoryRepository;
import qc.module.platform.dto.uac.UacUserInfoDto;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 仓库出入库记录信息接口Service
 *
 * @author QuCheng Tech
 * @create 2024/11/11
 */
@Service
public class EhsWarehouseInventoryService {

    @Autowired
    private EhsWarehouseInventoryRepository repository;

    /**
     * 查询仓库出入库记录
     *
     * @param condition 查询条件DTO
     * @return List<WareHouseInventoryDto>
     * @author QuCheng Tech
     * @since 2024/11/12
     */
    public List<WareHouseInventoryDto> query(WareHouseInventoryQueryConditionDto condition) throws QCPromptException {
        //1.查询条件有效性验证
        if (condition == null) throw new QCPromptException("查询条件不能为空");
        if (StringUtils.isBlank(condition.getWarehouseid())) throw new QCPromptException("仓库ID不能为空");
        if (StringUtils.isBlank(condition.getBegintm())) throw new QCPromptException("起始时间不能为空");
        if (StringUtils.isBlank(condition.getEndtm())) throw new QCPromptException("截止时间不能为空");

        //查询时间处理
        Date beginDate = null;
        Date endDate = null;
        if (StringUtils.isNotBlank(condition.getBegintm())) {
            try {
                beginDate = DateUtil.parseDate(condition.getBegintm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的开始日期转换错误");
            }
        }
        if (StringUtils.isNotBlank(condition.getEndtm())) {
            try {
                endDate = DateUtil.parseDate(condition.getEndtm());
            } catch (Exception e) {
                // 时间转换错误，抛出自定义异常
                throw new QCPromptException("查询条件中的截止日期转换错误");
            }
        }
        Date finalBeginDate = beginDate;
        Date finalEndDate = endDate;

        LambdaQueryWrapper<EhsWarehouseInventory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsWarehouseInventory::getWarehouseid, condition.getWarehouseid())
                .and(q -> {
                    q.ge(EhsWarehouseInventory::getTm, finalBeginDate).le(EhsWarehouseInventory::getTm, finalEndDate);
                })
                .orderByDesc(EhsWarehouseInventory::getTm);
        List<EhsWarehouseInventory> ens = repository.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(ens)) {
            return EhsWarehouseInventoryMapper.MAPPER.toDtoList(ens);
        }
        return null;
    }

    /**
     * 获取指定仓库出入库记录
     *
     * @param id 出入库记录ID
     * @return WareHouseInventoryDto
     * @author QuCheng Tech
     * @since 2024/11/12
     */
    public WareHouseInventoryDto get(String id) {

        EhsWarehouseInventory en = repository.selectById(id);
        if (Objects.nonNull(en)) {
            return EhsWarehouseInventoryMapper.MAPPER.toDto(en);
        }
        return null;
    }

    /**
     * 仓库出入库填单
     * 每个出入库记录分为填单和复核2步，由不同人员进行操作；
     *
     * @param addDto
     * @param userInfo 操作用户信息
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/11/12
     */
    public String add(WareHouseInventoryAddDto addDto, UacUserInfoDto userInfo) {
        //1.DTO有效性验证
        if (addDto == null) return QCUnifyReturnValue.Warn("填写记录不能为空");
        if (StringUtils.isBlank(addDto.getWarehouseid())) return QCUnifyReturnValue.Warn("仓库ID不能为空");
        if (StringUtils.isBlank(addDto.getTm())) return QCUnifyReturnValue.Warn("时间不能为空");
        if (addDto.getOptype() < EhsWarehouseInventoryOperateTypeEnum.OUTBOUND.getIndex()
                || addDto.getOptype() > EhsWarehouseInventoryOperateTypeEnum.LIQUID_WASTE_DISPOSAL.getIndex())
            return QCUnifyReturnValue.Warn("操作类型不能为空");
        if (StringUtils.isBlank(addDto.getName())) return QCUnifyReturnValue.Warn("操作标题不能为空");

        EhsWarehouseInventory en = EhsWarehouseInventoryMapper.MAPPER.addDtoToEntity(addDto);
        en.setId(IdentifierUtil.randomUUID());
        en.setOpuserid(userInfo.getId());
        en.setOpusername(userInfo.getName());

        if (repository.insert(en) < 0x1) {
            return QCUnifyReturnValue.Warn("保存失败");
        }
        return QCUnifyReturnValue.Success();
    }

    /**
     * 仓库出入库复核
     * 每个出入库记录分为填单和复核2步，由不同人员进行操作；
     *
     * @param id 出入库记录ID
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/11/12
     */
    public String check(String id, UacUserInfoDto userInfo) {
        EhsWarehouseInventory en = repository.selectById(id);

        //判断复核人员与操作人员是否为同一人，是则提示
        if (userInfo.getId() == en.getOpuserid())
            return QCUnifyReturnValue.Warn("复核人员与操作人员不能是同一人。");

        LambdaUpdateWrapper<EhsWarehouseInventory> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(EhsWarehouseInventory::getId, id)
                .set(EhsWarehouseInventory::getChecktm, DateUtil.getNowDate())
                .set(EhsWarehouseInventory::getCheckuserid, userInfo.getId())
                .set(EhsWarehouseInventory::getCheckusername, userInfo.getName());

        repository.update(null, wrapper);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 删除
     *
     * @param id 出入库记录ID
     * @return 成功返回null，失败返回错误或提示信息
     * @author QuCheng Tech
     * @since 2024/11/12
     */
    public String delete(String id) {
        repository.deleteById(id);
        return QCUnifyReturnValue.Success();
    }

    /**
     * 获取指定仓库的出入库记录
     *
     * @param wareHouseId 仓库ID
     * @return List<WareHouseInventoryDto>
     * @author QuCheng Tech
     * @since 2024/11/12
     */
    public List<WareHouseInventoryDto> getByWareHouseId(String wareHouseId) {
        LambdaQueryWrapper<EhsWarehouseInventory> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(EhsWarehouseInventory::getWarehouseid, wareHouseId)
                .orderByDesc(EhsWarehouseInventory::getTm);
        List<EhsWarehouseInventory> ens = repository.selectList(wrapper);
        if (CollectionUtils.isNotEmpty(ens)) {
            return EhsWarehouseInventoryMapper.MAPPER.toDtoList(ens);
        }
        return null;
    }
}
